"""
将OPERA导出的表格转化为GDF可阅读的文本文件（顺便也更容易被pandas读取）
"""
import os.path
import re
import shutil
from io import StringIO

import pandas

def get_out_path (filepath):
    outputdir, filenamebase = os.path.split(filepath)
    filenamebase = os.path.splitext(filenamebase)[0]
    outpath = os.path.join(outputdir, filenamebase + ".txt")
    return outpath
def parse_faster(filepath, lengu_to_SI_unit=1.0, ):
    """
    :param filepath:
    :param lengu_to_SI_unit: table中所用的长度单位除以SI单位，如，若table中长度单位为mm，则lengu_to_SI_unit == 1e-3
    :return:
    """
    # outputdir, filenamebase = os.path.split(filepath)
    # filenamebase = os.path.splitext(filenamebase)[0]
    # outpath = os.path.join(outputdir, filenamebase + ".txt")

    N_HEADLINES = 30

    with open(filepath, 'r') as f:
        data_str = f.readlines()  # 第一行无用
    colnames = []
    i = 1
    for line in data_str[i:N_HEADLINES]:
        if line == ' 0\n':
            break
        colnames.append(re.findall(r'\s+[0-9]\s+([A-Za-z]+)', line)[0])
        i += 1

    # %%
    df = pandas.read_csv(StringIO(''.join(data_str[i + 1:])), sep=r'\s+', engine='python', header=None)
    df.columns = colnames
    df = df.drop_duplicates(["X", "Y", "Z"])  # 不删除则插值会报错

    df[["X", "Y", "Z"]] *= lengu_to_SI_unit

    # df["Z"] += .28
    df.to_csv(get_out_path(filepath), index=False, sep='\t')
    return df


def parse(filepath, lengu_to_SI_unit=1.0, ):
    """

    :param filepath:
    :param lengu_to_SI_unit: table中所用的长度单位除以SI单位，如，若table中长度单位为mm，则lengu_to_SI_unit == 1e-3
    :return:
    """
    outputdir, filenamebase = os.path.split(filepath)
    filenamebase = os.path.splitext(filenamebase)[0]
    outpath = os.path.join(outputdir, filenamebase + ".txt")

    BIG_NUM = 1000
    cols = []
    with open(filepath, 'r') as f:
        f.readline()  # 第一行无用
        for i in range(BIG_NUM):
            line = f.readline()
            if line == " 0\n":
                break
            cols.append(line.split(" ")[2])

    # %%
    df = pandas.read_table(filepath, sep=r'\s+', engine='python', skiprows=len(cols) + 2, header=None)
    df.columns = cols
    df = df.drop_duplicates(["X", "Y", "Z"])

    df[["X", "Y", "Z"]] *= lengu_to_SI_unit

    # df["Z"] += .28
    df.to_csv(outpath, index=False, sep='\t')
    return df


def check_Bdata(Bdata: pandas.DataFrame, z_start, z_end):
    Bdata_axis = Bdata[Bdata['X'] == 0][Bdata["Y"] == 0][Bdata["Z"] >= z_start][Bdata["Z"] <= z_end]
    return (Bdata_axis["BY"] * (z_end - z_start)).sum() / len(Bdata_axis)


if __name__ == '__main__':
    filepaths = [
        # r"F:\Users\Zhang\AppData\Local\OperaFEA Batch Files\21.1\CommonBatches\tinahaosun\LGB2-gap\LGB2-use\LGB2-bao\LGB2-use\LGB2-use\LGB2-use\LGB2-use\LGB2-use\LGB2-use-1\assemble-adjustment\B-exported\pole-4.table",
        # r"F:\Users\Zhang\AppData\Local\OperaFEA Batch Files\21.1\CommonBatches\tinahaosun\LGB2-gap\LGB2-use\LGB2-bao\LGB2-use\LGB2-use\LGB2-use\LGB2-use\LGB2-use\LGB2-use-1\assemble-adjustment\B-exported\pole-%d.table" % i
        # for i in range(1, 5)
        # r"\\zhang-pc-nsrl\CommonBatches2\tinahaosun\LGB2-gap\LGB2-use\LGB2-bao\LGB2-use\LGB2-use\LGB2-use\LGB2-use\LGB2-use\LGB2-use-1\LGB2-use\LGB2-use\exported\LGB-52.table"
        # r"F:\Users\Zhang\AppData\Local\OperaFEA Batch Files\21.1\CommonBatches\tinahaosun\LGB2-gap\LGB2-use\LGB2-bao\LGB2-use\LGB2-use\LGB2-use\LGB2-use\LGB2-use\LGB2-use-1\LGB2-use\LGB2-use\4\exported\LGB2-8-4.table",
        # r"F:\Users\Zhang\AppData\Local\OperaFEA Batch Files\21.1\CommonBatches\tinahaosun\LGB2-gap\LGB2-use\LGB2-bao\LGB2-use\LGB2-use\LGB2-use\LGB2-use\LGB2-use\LGB2-use-1\LGB2-use\LGB2-use\4\LGB2-20-1.op3.table"
        # r'F:\Users\Zhang\AppData\Local\OperaFEA Batch Files\21.1\CommonBatches\tinahaosun\LGB2-gap\LGB2-use\LGB2-bao\LGB2-use\LGB2-use\LGB2-use\LGB2-use\LGB2-use\LGB2-use-1\LGB2-use\LGB2-use\4\LGB2-use\150mm\LGB2-34-1.op3.table'
        # r'\\ZHANG-PC-NSRL\CommonBatches2\tinahaosun\LGB2-gap\LGB2-use\LGB2-bao\LGB2-use\LGB2-use\LGB2-use\LGB2-use\LGB2-use\LGB2-use-1\LGB2-use\LGB2-use\4\LGB2-use\150mm\current\7-1.op3.table'
        # r"\\ZHANG-PC-NSRL\CommonBatches2\tinahaosun\1\LGB2-15.op3.table"
        # r"\\DESKTOP-XTVPXNT\dipole-1\dipole-5.op3.table"
        # r"\\DESKTOP-XTVPXNT\dipole-1\LGB2-11.op3.table"
        # r"\\DESKTOP-XTVPXNT\processing\LGB2-11-BH.op3.table"
        # r"\\DESKTOP-XTVPXNT\LGB1-use\LGB1-22-1.op3.table"
        # r'\\DESKTOP-XTVPXNT\LGB1-use\LGB1-107.op3.table'
        # r'\\DESKTOP-XTVPXNT\LGB1-use\wucha\poledisplacement-y\y--003.op3.table'
        # r"\\DESKTOP-XTVPXNT\processing\current\LGB2-11-current-1.op3.table"
        # r'\\DESKTOP-XTVPXNT\LGB3-use\LGB3-37.op3.table'
        # r"\\DESKTOP-XTVPXNT\LGB1-use\mechanical\LGB1-use-mechanical-2.op3.table"
        r"\\DESKTOP-XTVPXNT\LGB1-use\mechanical\LGB1-use-mechanical-3.op3.table"
    ]
    from _logging import logger
    for filepath in filepaths:
        df = parse_faster(filepath, 1e-3)
        logger.info("积分场 = %.10f, file=%s" % (check_Bdata(df, -500e-3, 1800e-3), filepath))
    if len(filepaths) == 1:
        shutil.copy(get_out_path(filepaths[0]), '../Bdata.txt')



